package game;

import javax.microedition.lcdui.game.LayerManager;

import main.Res;
import basic.RotatableSprite;

public class Tank extends Unit {
	protected double velocityX;
	protected double velocityY;
	protected double acceleration = 3;
	protected double maxSpeed = 10;
	protected double friction = 0.5;
	protected RotatableSprite tankSprite;
	protected RotatableSprite gunSprite;

	public Tank() {
		hp = MAX_HP;
		attack = 100;
		defend = 100;

		tankSprite = new RotatableSprite(Res.get().imgTank, 30, 30, 3);
		tankSprite.defineReferencePixel(15, 15);
		tankSprite.setFrameSequence(new int[] { 0, 1, 2 });

		gunSprite = new RotatableSprite(Res.get().imgTankGun, 30, 30, 1);
		gunSprite.defineReferencePixel(15, 15);

		velocityX = 0;
		velocityY = 0;
	}

	public void addToLayer(LayerManager layer) {
		layer.insert(tankSprite, 0);
		layer.insert(gunSprite, 0);
	}

	public void init(int x, int y) {
		hp = MAX_HP;
		velocityX = 0;
		velocityY = 0;
		positionX = x;
		positionY = y;
		setPosition(x, y);
	}

	protected void setPosition(int x, int y) {
		tankSprite.setRefPixelPosition(x, y);
		gunSprite.setRefPixelPosition(x + Res.random(3) - 1, y + Res.random(3)
				- 1);

	}

	protected void setRotation(int x, int y) {

	}

	public void update() {
		
		positionX += velocityX;
		positionY += velocityY;

		setPosition((int) positionX, (int) positionY);

		double d = Math.sqrt(velocityX * velocityX + velocityY * velocityY);
		if(d<friction){
			velocityX = 0;
			velocityY = 0;
			return;
		}
		tankSprite.nextFrame();
		double frictionX = velocityX * friction / d;
		double frictionY = velocityY * friction / d;
		velocityX -= frictionX;
		velocityY -= frictionY;
	}

	public void run(int x, int y) {

		double d = Math.sqrt(x * x + y * y);
		if (d == 0) {
			return;
		}
		velocityX += x * acceleration / d;
		if (velocityX > maxSpeed) {
			velocityX = maxSpeed;
		} else if (velocityX < -maxSpeed) {
			velocityX = -maxSpeed;
		}
		velocityY += y * acceleration / d;
		if (velocityY > maxSpeed) {
			velocityY = maxSpeed;
		} else if (velocityY < -maxSpeed) {
			velocityY = -maxSpeed;
		}
		tankSprite.setRotation(arc(x, y));
		gunSprite.setRotation(arc(x, y));
	}

	public void fire(int x, int y) {

	}
	
	public double getVelocityX(){
		return velocityX;
	}
	
	public double getVelocityY(){
		return velocityY;
	}

	public void revertVelocity(double ratio){
		velocityX *= -ratio;
		velocityY *= -ratio;
	}
}
